<?php

namespace Platform\Services\Pay;

use Platform\Services\BaseService;

class PayService extends BaseService {

    /**
     * 
     * @param type $userId
     * @param type $objectType
     * @param type $objectId
     * @param type $cash
     * @param type $userInfo
     * @return type
     */
    public function createPayOrder($userId, $objectType, $objectId, $cash, $userInfo) {
        $userId = intval($userId) ? intval($userId) : E("用户ID不能为空");
        $objectType = intval($objectType) ? intval($objectType) : E("对象类型不能为空");
        $objectId = intval($objectId) ? intval($objectId) : E("对象ID不能为空");
        $cash = doubleval($cash) ? doubleval($cash) : E("金额不能为空");
        switch ($objectType) {
            case 1:
                $videoInfo = service("Video/VideoService")->getVideoInfoById($objectId);
                if (empty($videoInfo)) {
                    E("对象不存在");
                }
                $beUserInfo = service("User/UserService")->getUserInfoByUserId($videoInfo['userId']);
                if (empty($beUserInfo)) {
                    E("被打赏对象不存在");
                }
        }
        $orderNo = $this->get_order_no();
        $createTime = time();
        $status = 0;
        $payOrderModel = model("Pay/PayOrder");
        $payOrderModel->setUserId($userId);
        $payOrderModel->setOrderNo($orderNo);
        $payOrderModel->setObjectType($objectType);
        $payOrderModel->setObjectId($objectId);
        $payOrderModel->setStatus($status);
        $payOrderModel->setCreateTime($createTime);
        $payOrderModel->setCash($cash);
        $payOrderModel->setUpdateTime(0);
        $payOrderModel->setUserNickname($userInfo['nickname']);
        $payOrderModel->setUserImg($userInfo['img']);
        $payOrderModel->setBeUserId($beUserInfo['id']);
        $payOrderModel->setBeUserImg($beUserInfo['img']);
        $payOrderModel->setBeUserNickname($beUserInfo['nickname']);
        $result = $payOrderModel->save();
        if ($result == FALSE) {
            $messages = $payOrderModel->getMessages();
            foreach ($messages as $message) {
                E($message, "\n");
            }
        }
        return $payOrderModel->toArray();
    }

    /**
     * 查看订单 
     */
    public function getPayOrderInfoById($id) {
        $id = intval($id) ? intval($id) : E("订单id不能为空");
        $payOrderModel = model('Pay/PayOrder');
        $payOrderInfo = $payOrderModel->getDataById($id);
        return $payOrderInfo;
    }

    /**
     * 查看订单 
     */
    public function getPayOrderByOrderNo($orderNo) {
        $orderNo = trim($orderNo) ? trim($orderNo) : E("订单号不能为空");
        $payOrderModel = model('Pay/PayOrder');
        $payOrderInfo = $payOrderModel->findFirstByOrderNo($orderNo);
        if ($payOrderInfo) {
            $payOrderInfo = $payOrderInfo->toArray();
        } else {
            E("订单不存在");
        }
        return $payOrderInfo;
    }

    /**
     * 订单确认
     */
    public function payOrderSuccess($id, $openId) {
        $id = intval($id) ? intval($id) : E("订单id不能为空");
        $this->db->begin();
        $payOrderModel = model("Pay/PayOrder");
        $payOrderInfoObject = $payOrderModel->getForUpdateDataById($id);
        if (empty($payOrderInfoObject)) {
            $this->db->rollback();
            E("订单不存在");
        }
        $payOrderInfo = $payOrderInfoObject->toArray();
        if ($payOrderInfo['status'] != 0) {
            $this->db->rollback();
            E("订单状态已确认");
        }
        //操作打赏用户数据
        $userModel = model("User/User");
        $userInfoObject = $userModel->getForUpdateDataById($payOrderInfo['userId']);
        if (empty($userInfoObject)) {
            $this->db->rollback();
            E("打赏用户不存在");
        }
        $userInfoObject->setMinisendCount($userInfoObject->getMinisendCount() + 1);
        $userInfoObject->setMinisendMoney($userInfoObject->getMinisendMoney() + $payOrderInfo['cash']);
        $result = $userInfoObject->save();
        if ($result === FALSE) {
            $this->db->rollback();
            E("操作打赏用户数据出错");
        }
        //操作被打赏用户数据
        $beUserInfoObject = $userModel->getForUpdateDataById($payOrderInfo['beUserId']);
        if (empty($beUserInfoObject)) {
            $this->db->rollback();
            E("打赏用户不存在");
        }
        $beUserInfoObject->setMinibegCount($beUserInfoObject->setMinibegCount() + 1);
        $beUserInfoObject->setMinibegMoney($beUserInfoObject->getMinibegMoney() + $payOrderInfo['cash']);
        $beUserInfoObject->setMoney($beUserInfoObject->getMoney() + $payOrderInfo['cash']);
        $result = $beUserInfoObject->save();
        if ($result === FALSE) {
            $this->db->rollback();
            E("操作被打赏用户数据出错");
        }
        //操作视频数据
        switch ($payOrderInfo['objectType']) {
            case "1":
                $redPacketVideoModel = model("Video/RedPacketVideo");
                $redPacketVideoInfo = $redPacketVideoModel->getForUpdateDataById($payOrderInfo['objectId']);
                if (!empty($redPacketVideoInfo)) {
                    $redPacketVideoInfo->setGetPacketCount($redPacketVideoInfo->getGetPacketCount() + 1);
                    $redPacketVideoInfo->setGetPacketMoney($redPacketVideoInfo->getGetPacketMoney() + $payOrderInfo['cash']);
                    $result = $redPacketVideoInfo->save();
                    if ($result === FALSE) {
                        $this->db->rollback();
                        E("操作被打赏视频数据出错");
                    }
                }
                break;
        }
        $payOrderInfoObject->setUpdateTime(time());
        $payOrderInfoObject->setStatus(1);
        $payOrderInfoObject->setOpenId($openId);
        $result = $payOrderInfoObject->save();
        if ($result === FALSE) {
            $this->db->rollback();
            E("操作订单数据出错");
        }
        $moneyRecordModel = model("Pay/MoneyRecord");
        $moneyRecordModel->setCreateTime(time());
        $moneyRecordModel->setType(1);
        $moneyRecordModel->setUserId($payOrderInfo['beUserId']);
        $moneyRecordModel->setMoney($payOrderInfo['cash']);
        $moneyRecordModel->setOpenId($openId);
        $result = $moneyRecordModel->save();
        if ($result === FALSE) {
            $this->db->rollback();
            E("添加流水日志出错");
        }
        $this->db->commit();
        return $payOrderInfo;
    }

    /*
     * 得到订单号
     */

    public function get_order_no() {
        $date_code = array('0',
            '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
            'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
            'N', 'O', 'P', 'Q', 'R', 'T', 'U', 'V', 'W', 'X', 'Y');
        $order_sn = date('y') .
                strtoupper(dechex(date('m'))) . $date_code[intval(date('d'))] .
                substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $order_sn;
    }

    /**
     * 获取我发送的红包记录
     * @param type $userId
     * @param type $p
     * @param type $psize
     */
    public function getMySendRedpacketList($userId, $p, $psize) {
        $p = intval($_POST['p']) ? intval($_POST['p']) : 1;
        $psize = intval($_POST['psize']) ? intval($_POST['psize']) : 10;
        $payOrderModel = model("Pay/PayOrder");
        $condition['status'] = 1;
        $condition['objectType'] = 1;
        $condition['userId'] = $userId;
        $list = $payOrderModel->getLists($condition, array(), "", $p, $psize);
        return $list;
    }

    /**
     * 获取视频乞讨到的红包记录
     * @param type $userId
     * @param type $p
     * @param type $psize
     */
    public function getVideoBegRedpacketList($videoId, $p, $psize) {
        $p = intval($_POST['p']) ? intval($_POST['p']) : 1;
        $psize = intval($_POST['psize']) ? intval($_POST['psize']) : 10;
        $payOrderModel = model("Pay/PayOrder");
        $condition['status'] = 1;
        $condition['objectType'] = 1;
        $condition['objectId'] = $videoId;
        $list = $payOrderModel->getLists($condition, array(), "id desc", $p, $psize);
        return $list;
    }

    public function withdrawMoney($userId, $money) {
        $id = intval($userId) ? intval($userId) : E("用户id不能为空");
        $money = doubleval($money) ? doubleval($money) : E("金额不能为空");
        $this->db->begin();
        $userModel = model("User/User");
        $userInfoObject = $userModel->getForUpdateDataById($userId);
        if (empty($userInfoObject) || empty($userInfoObject->getQmzfOpenId())) {
            $this->db->rollback();
            E("用户不存在");
        }
        $openId = $userInfoObject->getQmzfOpenId();
        if ($money > $userInfoObject->getMoney()) {
            $this->db->rollback();
            E("余额不足");
        }
        $orderNo = $this->get_order_no();
        //调用微信提现
        try {
            $cash = doubleval(substr(sprintf("%.3f", $money / 1.02, 2), 0, -1));
            $wxResult = lib("WxPayQMZF")->enterprisePayment($openId, $orderNo, $cash);
            $wxResult = json_encode($wxResult);
        } catch (\Exception $exc) {
            $this->db->rollback();
            E("支付失败：" . $exc->getMessage());
        }
        $moneyRecordModel = model("Pay\MoneyRecord");
        $moneyRecordModel->setCreateTime(time());
        $moneyRecordModel->setType(2);
        $moneyRecordModel->setUserId($userId);
        $moneyRecordModel->setMoney($money);
        $moneyRecordModel->setOpenId($openId);
        $moneyRecordModel->setOrderNo($orderNo);
        $moneyRecordModel->setResultJson($wxResult);
        $moneyRecordModel->setCash($cash);
        $result = $moneyRecordModel->save();
        if ($result === FALSE) {
            $this->db->rollback();
            E("添加流水日志出错");
        }
        $userInfoObject->setMoney(doubleval(doubleval($userInfoObject->getMoney()) - doubleval($money)));
        $result === $userInfoObject->save();
        if ($result === FALSE) {
            $this->db->rollback();
            E("保存用户信息失败");
        }
        $this->db->commit();
    }

}

?>